package cn.lblbc.webbrowser.utils

import android.content.Context
import android.content.SharedPreferences
import cn.lblbc.webbrowser.models.Bookmark
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class BookmarkManager(context: Context) {
    private val prefs: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    private val gson = Gson()
    
    companion object {
        private const val PREFS_NAME = "bookmarks_prefs"
        private const val KEY_BOOKMARKS = "bookmarks"
    }
    
    fun getBookmarks(): List<Bookmark> {
        val json = prefs.getString(KEY_BOOKMARKS, null) ?: return emptyList()
        val type = object : TypeToken<List<Bookmark>>() {}.type
        return try {
            gson.fromJson(json, type)
        } catch (e: Exception) {
            emptyList()
        }
    }
    
    fun addBookmark(bookmark: Bookmark) {
        val bookmarks = getBookmarks().toMutableList()
        
        // 检查是否已存在相同URL的书签
        val existingIndex = bookmarks.indexOfFirst { it.url == bookmark.url }
        if (existingIndex != -1) {
            // 如果存在，更新它
            bookmarks[existingIndex] = bookmark
        } else {
            // 如果不存在，添加新的
            bookmarks.add(bookmark)
        }
        
        saveBookmarks(bookmarks)
    }
    
    fun removeBookmark(url: String) {
        val bookmarks = getBookmarks().toMutableList()
        bookmarks.removeAll { it.url == url }
        saveBookmarks(bookmarks)
    }
    
    fun isBookmarked(url: String): Boolean {
        return getBookmarks().any { it.url == url }
    }
    
    private fun saveBookmarks(bookmarks: List<Bookmark>) {
        val json = gson.toJson(bookmarks)
        prefs.edit().putString(KEY_BOOKMARKS, json).apply()
    }
}